package jus.aor.mobilagent.kernel;

import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.jar.JarException;

public class BAMLoader extends URLClassLoader{
	//static URL[] tabBAM=new URL[]{};
	//HashMap<String, Jar> classmap;
	private Map<String,byte[]> classmap = new HashMap<String,byte[]>();
	Jar jarfile;

	public BAMLoader() {
		super(new URL[]{},null);
	//	classmap=new HashMap<String, Jar>();
	}
	public BAMLoader(ClassLoader loader) {
		super(new URL[]{},loader);
		classmap=new HashMap<String, byte[]>();
	}

	public void addURL(String jar) {
			try {
				if (jarfile == null){
					jarfile = new Jar(jar);
					integrateCode(jarfile);
				}
				else{
					Jar j = new Jar(jar);
					integrateCode(j);
				}
				super.addURL(new URL("file:/"+jar));
			} catch (JarException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
	}
	public Jar extractCode(){
		return jarfile;		
	}
	
	public Class<?> findClass(String className) throws ClassNotFoundException {

		Class<?> result = null;  
		byte classByte[]; 	
		if(classmap.containsKey(className)){
			classByte = classmap.get(className);
			result = defineClass(className, classByte, 0, classByte.length);
			return result;
		}
		else throw new ClassNotFoundException(className);
	}
	
	public void integrateCode(Jar jar) {
		if (jarfile == null){
			jarfile = jar;
			integrateCode(jarfile);
		}
		String nomClass;
		byte[] code ;
		Entry<String,byte[]> valeur;
		Iterable<Entry<String, byte[]>> tmp = jar.classIterator();
		Iterator<Entry<String, byte[]>> it = tmp.iterator();
		while(it.hasNext()){
			valeur = it.next();
			nomClass = valeur.getKey();
			code = valeur.getValue();
			classmap.put(jar.formatClassName(nomClass), code);
		}
	}
	public String toString(){
		String g = null ;
		String nomClass;
		Entry<String,byte[]> valeur;
		Iterable<Entry<String, byte[]>> tmp = jarfile.classIterator();
		Iterator<Entry<String, byte[]>> it = tmp.iterator();
		while(it.hasNext()){
		valeur = it.next();
			nomClass = valeur.getKey();
			g = g +" "+jarfile.formatClassName(nomClass);
		}
		return g;
	}
	public void print() {
		classmap.toString();
	}
		
}
